package com.freewater.javabase.demo.network.cookie;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * 设置CookieManager之后，对于你使用URL类链接的http服务器，Java回存储这些服务器发送的所有cookie，再在后续的请求向
 * 这些服务器发送存储的cookie；
 * 第一方cookie与第三方cookie：https://blog.csdn.net/thlzjfefe/article/details/118278542
 */
public class CookieManagerDemo {
    public static void main(String[] args) throws MalformedURLException {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); // 只接受第一方cookie，不接受第三方cookie
        CookieHandler.setDefault(cookieManager); // 设置为默认的CookieHandler
        URL url = new URL("https://www.baidu.com");
        try (BufferedInputStream is = new BufferedInputStream(url.openStream());
             InputStreamReader reader = new InputStreamReader(is)) {
            char[] buffer = new char[1024];
            int read;
            while ((read = reader.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, read));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = new URL("https://image.baidu.com"); // 再次请求则会带上之前返回的cookie
    }

    /**
     * 自定义的Cookie接收策略
     */
    class NoGovernmentCookies implements CookiePolicy {

        @Override
        public boolean shouldAccept(URI uri, HttpCookie cookie) {
            if (uri.getAuthority().toLowerCase().endsWith("gov")
                    || cookie.getDomain().toLowerCase().endsWith("gov")) {
                return false;
            }
            return true;
        }
    }
}
